﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Yoozoo.Extension
{
    // 用于UI内带有MeshRenderer的特效混排
    // 将这个脚本挂在特效的根节点，设置SortingLayerName和SortingOrder

    public class SetSortingLayerAndOrder : MonoBehaviour
    {
        public string SortingLayerName = "Default";
        public int SortingOrder = 25;
        public bool Inherit = true;

        void Start()
        {
            if (Inherit) SortingOrder = GetParentSortingOrder(transform);
            var renderer = GetComponentsInChildren<Renderer>(true);
            foreach (var r in renderer)
            {
                r.sortingLayerName = SortingLayerName;
                r.sortingOrder = SortingOrder;
            }
        }
        
        private int GetParentSortingOrder(Transform transform)
        {
            int max = 0;
            Transform target = transform;
            while (true && target!=null && target.parent!=null)
            {
                target = target.parent;
                int sortingOrder = this.GetSortingOrder(target);
                if (sortingOrder != int.MinValue)
                {
                    return sortingOrder;
                }
                max++;
                if (max >= 20)
                {
                    return SortingOrder;
                }
            }
            return SortingOrder;
        }
        
        int GetSortingOrder(Transform child)
        {
            Canvas canvas = child.GetComponent<Canvas>();
            if (canvas != null)
            {
                return canvas.sortingOrder;
            }
            Renderer renderer = child.GetComponent<Renderer>();
            if (renderer != null)
            {
                return renderer.sortingOrder;
            }
            return int.MinValue;
        }

#if UNITY_EDITOR
        private void OnValidate()
        {
            var renderer = GetComponentsInChildren<Renderer>(true);
            foreach (var r in renderer)
            {
                r.sortingLayerName = SortingLayerName;
                r.sortingOrder = SortingOrder;
            }
        }
#endif

    }
}
